<?php

namespace app\modules\Product\controllers;

use Yii;
use app\modules\Product\models\Product;
use app\modules\Product\models\Word;
use app\modules\Product\models\ProductSearch;
use app\modules\Product\models\Template;
use app\modules\Product\models\Excel;
use app\modules\Order\models\Order;
use app\modules\Order\models\OrderCustomer;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * 统计管理
 */
class StatisticController extends Controller
{
     /**
     * @inheritdoc
     */
    public function behaviors()
    {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['post'],
				],
			],
			'access' => [
				'class' => AccessControl::className(),
				'rules' => [
					['allow' => true, 'actions' => ['index','create','view','update','delete', 'clone', 'trip', 'save', 'sort', 'word', 'order-excel','lines','excel','load'], 'roles' => ['@']],
				],
			],
		];
    }

    public function actionIndex()
    {
        return $this->render('index');
    }


    /*
     *  航线生成 Excel
     *
     */
    public function actionLines()
    {
        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->line_search(Yii::$app->request->queryParams);
       
        return  $this->render('lines',['searchModel' => $searchModel,
            'dataProvider' => $dataProvider]);
    }


    public function actionExcel(){

        $searchModel = new ProductSearch();
        $dataProvider = $searchModel->line_search(Yii::$app->request->queryParams);

        $objPHPExcel = new \PHPExcel();
        $sheet = $objPHPExcel->getActiveSheet(0);
        $sheet->setTitle('航线列表');
        $sheet->getDefaultStyle()->getFont()->setSize(12)->setName('微软雅黑');
        $sheet->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        $sheet->getColumnDimension('A')->setWidth(6);// 设置宽度
        $sheet->getColumnDimension('B')->setWidth(8);// 设置宽度
        $sheet->getColumnDimension('C')->setWidth(8);// 设置宽度
        $sheet->getColumnDimension('D')->setWidth(16);// 设置宽度
        $sheet->getColumnDimension('E')->setWidth(16);// 设置宽度
        $sheet->getColumnDimension('F')->setWidth(16);// 设置宽度
        $sheet->getColumnDimension('G')->setWidth(40);// 设置宽度
        $sheet->getColumnDimension('H')->setWidth(16);// 设置宽度
        $sheet->getColumnDimension('I')->setWidth(16);// 设置宽度
        $sheet->getColumnDimension('J')->setWidth(16);// 设置宽度

        $sheet->getColumnDimension('R')->setWidth(20);// 设置宽度
        $sheet->getColumnDimension('S')->setWidth(20);// 设置宽度
        $sheet->getColumnDimension('T')->setWidth(20);// 设置宽度

        $titleArray = ['#','类型','区域','邮轮公司','邮轮名称','团号','团队名称','出发日期','返回日期','出发城市','返回城市','人数','直客','同业','提交','付款','占位','总收入','直客收入','同行收入','状态'];

        $sheet->fromArray($titleArray, NULL, 'A1');

        foreach($dataProvider->getModels() as $key=>$model){
            $sheet->setCellValue(sprintf("A%d",$key+2),$key+1);
            $sheet->setCellValue(sprintf("B%d",$key+2),Yii::$app->params['product_type'][$model->type]);
            $sheet->setCellValue(sprintf("C%d",$key+2),Yii::$app->params['line'][$model->line]);
            $sheet->setCellValue(sprintf("D%d",$key+2),$model->cruise->supplier->company);
            $sheet->setCellValue(sprintf("E%d",$key+2),$model->cruise->name);
            $sheet->setCellValue(sprintf("F%d",$key+2),$model->code);
            $sheet->setCellValue(sprintf("G%d",$key+2),$model->name);
            $sheet->setCellValue(sprintf("H%d",$key+2),isset($model->go_time)?date("Y年m月d日",strtotime($model->go_time)):'未设置');
            $sheet->setCellValue(sprintf("I%d",$key+2),isset($model->return_time)?date("Y年m月d日",strtotime($model->return_time)):'未设置');
            $sheet->setCellValue(sprintf("J%d",$key+2),Yii::$app->params['city'][$model->from_city]);
            $sheet->setCellValue(sprintf("K%d",$key+2),Yii::$app->params['city'][$model->to_city]);
            $sheet->setCellValue(sprintf("L%d",$key+2),$model->getCustomerNums(0));
            $sheet->setCellValue(sprintf("M%d",$key+2),$model->getCustomerNums(1));
            $sheet->setCellValue(sprintf("N%d",$key+2),$model->getCustomerNums(2));
            $sheet->setCellValue(sprintf("O%d",$key+2),$model->getStatusCustomerNums(4));
            $sheet->setCellValue(sprintf("P%d",$key+2),$model->getStatusCustomerNums(3));
            $sheet->setCellValue(sprintf("Q%d",$key+2),$model->getStatusCustomerNums(1));
            $sheet->setCellValue(sprintf("R%d",$key+2),'¥'.$model->getSourceOrderPrice(0));
            $sheet->setCellValue(sprintf("S%d",$key+2),'¥'.$model->getSourceOrderPrice(1));
            $sheet->setCellValue(sprintf("T%d",$key+2),'¥'.$model->getSourceOrderPrice(2));
            $sheet->setCellValue(sprintf("U%d",$key+2),Yii::$app->params['status'][$model->status]);
        }

        foreach($dataProvider->getModels() as $key=>$model){

            $objWorkSheet = $objPHPExcel->createSheet($key+1);

            $objWorkSheet->setTitle(date("ymd",strtotime($model->go_time)).$model->cruise->name);
            $objWorkSheet->getDefaultStyle()->getFont()->setSize(12)->setName('微软雅黑');
            $objWorkSheet->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

            $objWorkSheet->getColumnDimension('A')->setWidth(20);// 设置宽度
            $objWorkSheet->getColumnDimension('B')->setWidth(20);// 设置宽度
            $objWorkSheet->getColumnDimension('C')->setWidth(16);// 设置宽度
            $objWorkSheet->getColumnDimension('D')->setWidth(16);// 设置宽度
            $objWorkSheet->getColumnDimension('E')->setWidth(16);// 设置宽度
            $objWorkSheet->getColumnDimension('F')->setWidth(16);// 设置宽度
            $objWorkSheet->getColumnDimension('G')->setWidth(16);// 设置宽度
            $objWorkSheet->getColumnDimension('H')->setWidth(16);// 设置宽度
            $objWorkSheet->getColumnDimension('I')->setWidth(16);// 设置宽度
            $objWorkSheet->getColumnDimension('J')->setWidth(16);// 设置宽度
            $objWorkSheet->getColumnDimension('K')->setWidth(20);// 设置宽度
            $objWorkSheet->getColumnDimension('L')->setWidth(20);// 设置宽度
            $objWorkSheet->getColumnDimension('O')->setWidth(20);// 设置宽度
            $objWorkSheet->getColumnDimension('R')->setWidth(20);// 设置宽度
            $objWorkSheet->getColumnDimension('S')->setWidth(20);// 设置宽度
            $objWorkSheet->getColumnDimension('T')->setWidth(20);// 设置宽度
            $i = 0;
           
            foreach($model->allOrder as $order){

                $titleArr = ['订单号','销售姓名','来源','公司名称','联系人','联系电话','状态','舱房金额','优惠额度','优惠备注','附加费金额'];
                //获取附加费条数
                $order_price_num = count($order->prices);
                if($order_price_num>0){
                    for($num=1;$num<=$order_price_num;$num++){
                         $titleArr[] = '附加费项目'.$num; 
                         $titleArr[] = '金额'; 
                         $titleArr[] = '人数'; 
                    }
                }
                $titleArr[] = '总金额';
                $titleArr[] = '订单备注';

                $orderArr = [$order->code,$order->member->profile->name,yii::$app->params['order_source'][$order->source],$order->company,$order->username,$order->phone,yii::$app->params['order_status'][$order->status],$order->total_sale,$order->sale_price,$order->price_desc,$order->priceSum];
                foreach($order->prices as $prices){
                     $orderArr[] = $prices->typeObj->name;
                     $orderArr[] = $prices->total_price;
                     $orderArr[] = $prices->num;
                }

                $orderArr[] = $order->price;
                $orderArr[] = $order->remark;

                $objWorkSheet->fromArray($titleArr, NULL,sprintf("A%d",$i+1));
                $objWorkSheet->getStyle(sprintf("A%d",$i+1))->getFont()->setSize(13)->setBold(true)->setName('微软雅黑')->getColor()->setARGB('000000');
                $i++;
                $objWorkSheet->fromArray($orderArr, NULL,sprintf("A%d",$i+1));
                $objWorkSheet->setCellValueExplicit(sprintf("A%d",$i+1),$order->code,\PHPExcel_Cell_DataType::TYPE_STRING);
                $i++;

                foreach($order->room as $key=>$room){
                    foreach($room->orderRoomCustomer as $customer){
                        $objWorkSheet->setCellValueExplicit(sprintf("A%d",$i+1),$room->order->code,\PHPExcel_Cell_DataType::TYPE_STRING);
                        $objWorkSheet->setCellValue(sprintf("B%d",$i+1),sprintf("房间%d",$key+1));
                        if($model->stock == 1){
                            $objWorkSheet->setCellValue(sprintf("C%d",$i+1),$room->productRoom->room->name.$room->productRoom->room->code.'-'.$room->productRoom->people.'人间');
                        }elseif($model->stock == 2){
                            $t = json_decode($model->rooms, true);
                            $objWorkSheet->setCellValue(sprintf("C%d",$i+1),$t[$room->room_id]['name']);
                        }
                        $objWorkSheet->setCellValue(sprintf("D%d",$i+1),$customer->orderCustomer->first_name);
                        $objWorkSheet->setCellValue(sprintf("E%d",$i+1),$customer->orderCustomer->last_name);
                        $objWorkSheet->setCellValue(sprintf("F%d",$i+1),$customer->orderCustomer->en_first_name);
                        $objWorkSheet->setCellValue(sprintf("G%d",$i+1),$customer->orderCustomer->en_last_name);
                        $objWorkSheet->setCellValue(sprintf("H%d",$i+1),$customer->orderCustomer->phone);
                        $objWorkSheet->setCellValue(sprintf("I%d",$i+1),yii::$app->params['gender'][$customer->orderCustomer->gender]);
                        $objWorkSheet->setCellValue(sprintf("J%d",$i+1),isset($customer->orderCustomer->birthday)?date("Y/m/d",strtotime($customer->orderCustomer->birthday)):'');
                        $objWorkSheet->setCellValue(sprintf("K%d",$i+1),$customer->orderCustomer->native);
                        $objWorkSheet->setCellValue(sprintf("L%d",$i+1),$customer->orderCustomer->country);
                        $objWorkSheet->setCellValue(sprintf("M%d",$i+1),$customer->orderCustomer->passport);
                        $objWorkSheet->setCellValue(sprintf("N%d",$i+1),$customer->orderCustomer->passport_add);
                        $objWorkSheet->setCellValue(sprintf("O%d",$i+1),isset($customer->orderCustomer->passport_grant)?date("Y/m/d",strtotime($customer->orderCustomer->passport_grant)):'');
                        $objWorkSheet->setCellValue(sprintf("P%d",$i+1),isset($customer->orderCustomer->passport_date)?date("Y/m/d",strtotime($customer->orderCustomer->passport_date)):'');
                        $objWorkSheet->setCellValue(sprintf("Q%d",$i+1),yii::$app->params['passport_type'][$customer->orderCustomer->passport_type]);
                        $objWorkSheet->setCellValue(sprintf("R%d",$i+1),'房号'.$room->code);
                        $i++;
                    }
                }

                $i++;

            }
        }
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $fileName = sprintf("%s.xlsx",uniqid());
        $path = 'uploads/excel/'.date('Ym').'/';
        if(!is_dir($path)){  
              mkdir($path,0777,true);  
        }
        $file = $path.$fileName;
        $objWriter->save($file);

        $file_name = "航线列表.xlsx";

        $file_arr = ['file_path'=> $file,'file_name'=>$file_name];

        return json_encode($file_arr);

    }


    public function actionLoad($file_path,$file_name){

        if(file_exists($file_path)){
            header("Content-type: application/octet-stream");    
            header("Accept-Ranges: bytes");    
            header("Accept-Length: " . filesize($file_path));    
            header("Content-Disposition: attachment; filename=" .$file_name);    
            @readfile($file_path);
        }else{
            return false;
        }       

    }

   
    

}
